<template>
  <div>
    <el-upload
        class="upload-demo"
        :on-change="handleChange"
        :show-file-list="false"
        :auto-upload="false"
        action=""
    >
      <el-button size="small" type="primary" style="margin-bottom:15px;"
      >读取excel文件
      </el-button
      >
    </el-upload>
    <el-table
        border
        height="600"
        :data="tableData"
        :default-sort = "{prop: 'cnt', order: 'descending'}"
    >
      <el-table-column align="center" label="关键词" prop="name"></el-table-column>
      <el-table-column align="center" label="出现次数" prop="cnt" sortable></el-table-column>
    </el-table>
  </div>

</template>

<script>
import * as xlsx from "xlsx";

export default {
  name: "tool",
  data() {
    return {
      tableData: [],
      fileContent: '',
      file: '',
      data: ''
    }
  },
  methods: {
    handleChange(file, fileList) {
      this.fileContent = file.raw
      const fileName = file.name
      const fileType = fileName.substring(fileName.lastIndexOf('.') + 1)
      if (this.fileContent) {
        if (fileType === 'xlsx' || fileType === 'xls') {
          this.importfile(this.fileContent)
        } else {
          this.$message({
            type: 'warning',
            message: '附件格式错误，请重新上传！'
          })
        }
      } else {
        this.$message({
          type: 'warning',
          message: '请上传附件！'
        })
      }
    },
    importfile(obj) {
      const that = this
      const reader = new FileReader()
      reader.readAsArrayBuffer(obj)
      reader.onload = function () {
        const buffer = reader.result
        const bytes = new Uint8Array(buffer)
        const length = bytes.byteLength
        let binary = ''
        for (let i = 0; i < length; i++) {
          binary += String.fromCharCode(bytes[i])
        }
        const XLSX = require('xlsx')
        const wb = XLSX.read(binary, {
          type: 'binary'
        })
        const outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
        let arr = []
        that.tableData = []
        outdata.map(item => {
          arr = arr.concat(item.__EMPTY.split(" "))

        })
        let obj={}
        arr.forEach(item=>{
            if(obj[item]){
              obj[item]+=1
            }else {
              obj[item]=1
            }
        })
        console.log(obj)
        that.tableData=Object.keys(obj).map((key)=>{
          return {name:key,cnt:obj[key]}
        })

        // for (var i = 0; i < arr.length;) {
        //   var count = 0;
        //   for (var j = i; j < arr.length; j++) {
        //     if (arr[i] == arr[j]) {
        //       count++;
        //     }
        //   }
        //   console.log(arr)
        //   console.log(arr[i])
        //   that.tableData.push({
        //     'name': arr[i],
        //     'cnt': count
        //   });
        //   i += count
        // }
      }
    },
  }
}
</script>

<style scoped>

</style>